<template>
  <div class="breeding-info">
    <!-- 养殖信息 -->
    <div class="info-section">
      <div class="info-header">
        <h4 class="info-title">养殖信息 <span class="info-count">设置 {{ Object.keys(localData).length }}</span></h4>
        <div class="info-actions">
          <el-button type="primary" size="small" @click="openBreedingDialog">
            <el-icon><Setting /></el-icon>
            设置
          </el-button>
        </div>
      </div>
      <div class="info-grid">
        <div class="info-item">
          <label>品种:</label>
          <span>{{ localData.variety || '暂无数据' }}</span>
        </div>
        <div class="info-item">
          <label>来源:</label>
          <span>{{ localData.source || '暂无数据' }}</span>
        </div>
        <div class="info-item">
          <label>饲养天数:</label>
          <span>{{ localData.feedingDays ? `${localData.feedingDays}天` : '暂无数据' }}</span>
        </div>
        <div class="info-item">
          <label>饲料品牌:</label>
          <span>{{ localData.feedBrand || '暂无数据' }}</span>
        </div>
        <div class="info-item">
          <label>饲养负责人:</label>
          <span>{{ localData.responsiblePerson || '暂无数据' }}</span>
        </div>
        <div class="info-item">
          <label>出栏日期:</label>
          <span>{{ localData.productionDate || '暂无数据' }}</span>
        </div>
      </div>
    </div>

    <!-- 保健信息 -->
    <div class="info-section">
      <div class="info-header">
        <h4 class="info-title">保健信息 <span class="info-count">新增于 {{ healthData.length }}</span></h4>
        <el-button type="primary" size="small" @click="addHealth">
          <el-icon><Plus /></el-icon>
          新增行
        </el-button>
      </div>
      <div class="health-table">
        <el-table :data="healthData" border>
          <el-table-column prop="feedingDays" label="饲养天数" width="120">
            <template #default="{ row }">
              <el-input 
                v-if="row.isEditing" 
                v-model="row.feedingDays" 
                size="small" 
                type="number" 
                placeholder="必填，仅数字，最多5位"
                min="0"
                max="99999"
                @input="validateFeedingDays(row)"
              />
              <span v-else>{{ row.feedingDays }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="healthMethod" label="保健方式" width="150">
            <template #default="{ row }">
              <el-input 
                v-if="row.isEditing" 
                v-model="row.healthMethod" 
                size="small" 
                placeholder="必填，中文和字母，不允许特殊字符，最多30字符"
                maxlength="30"
                @input="validateHealthMethod(row)"
              />
              <span v-else>{{ row.healthMethod }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="healthApproach" label="保健方法" width="150">
            <template #default="{ row }">
              <el-input 
                v-if="row.isEditing" 
                v-model="row.healthApproach" 
                size="small" 
                placeholder="必填，中文和字母，不允许特殊字符，最多30字符"
                maxlength="30"
                @input="validateHealthApproach(row)"
              />
              <span v-else>{{ row.healthApproach }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <template v-if="row.isEditing">
                <el-button type="success" size="small" link @click="saveHealth(row)">
                  <el-icon><View /></el-icon>
                  保存
                </el-button>
                <el-button type="info" size="small" link @click="cancelHealth(row)">
                  <el-icon><Close /></el-icon>
                  取消
                </el-button>
              </template>
              <template v-else>
                <el-button type="primary" size="small" link @click="editHealth(row)">
                  <el-icon><Edit /></el-icon>
                  修改
                </el-button>
                <el-button type="danger" size="small" link @click="deleteHealth(row)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 动检证 -->
    <div class="info-section">
      <h4 class="info-title">动检证</h4>
      <div class="certificate-gallery">
        <div v-for="cert in quarantineCertificates" :key="cert.id" class="certificate-item">
          <el-image :src="cert.url" fit="cover" class="certificate-img">
            <template #error>
              <div class="image-placeholder">
                <el-icon><Document /></el-icon>
              </div>
            </template>
          </el-image>
          <el-button 
            type="danger" 
            size="small" 
            circle 
            class="remove-btn"
            @click="removeCertificate(cert)"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <div class="add-certificate" v-if="quarantineCertificates.length < 9">
          <el-upload
            action="#"
            :show-file-list="false"
            :before-upload="handleCertificateUpload"
            accept="image/*"
            :disabled="quarantineCertificates.length >= 9"
          >
            <div class="upload-area">
              <el-icon><Plus /></el-icon>
              <div>新增</div>
              <div class="upload-tip">最多9张照片</div>
            </div>
          </el-upload>
        </div>
      </div>
    </div>

    <!-- 养殖信息编辑弹出框 -->
    <el-dialog
      v-model="breedingDialogVisible"
      :title="isEditMode ? '修改养殖信息' : '添加养殖信息'"
      width="500px"
      @close="handleBreedingDialogClose"
      :close-on-click-modal="false"
      :before-close="handleBreedingBeforeClose"
    >
      <el-form 
        :model="breedingForm" 
        :rules="breedingRules" 
        ref="breedingFormRef" 
        label-width="100px"
        label-position="top"
      >
        <el-form-item label="*品种" prop="variety" required>
          <el-input 
            v-model="breedingForm.variety" 
            placeholder="请输入品种"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="*来源" prop="source" required>
          <el-input 
            v-model="breedingForm.source" 
            placeholder="请输入来源"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="*饲养天数" prop="feedingDays" required>
          <el-input 
            v-model.number="breedingForm.feedingDays" 
            type="number"
            placeholder="请输入饲养天数"
            min="0"
            max="99999"
            maxlength="5"
          />
        </el-form-item>
        <el-form-item label="*饲料品牌" prop="feedBrand" required>
          <el-input 
            v-model="breedingForm.feedBrand" 
            placeholder="请输入饲料品牌"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="*饲养负责人" prop="responsiblePerson" required>
          <el-input 
            v-model="breedingForm.responsiblePerson" 
            placeholder="请输入饲养负责人"
            maxlength="30"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="*出栏日期" prop="productionDate" required>
          <el-date-picker 
            v-model="breedingForm.productionDate" 
            type="date" 
            placeholder="请选择出栏日期"
            format="YYYY年MM月DD日"
            value-format="YYYY年MM月DD日"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelBreedingDialog">取消</el-button>
        <el-button type="primary" @click="saveBreedingDialog">
          {{ isEditMode ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Setting,
  View,
  Close,
  Plus,
  Edit,
  Delete,
  Document,
  Picture
} from '@element-plus/icons-vue'

const props = defineProps<{ 
  data: any,
  healthData: any[],
  quarantineCertificates: any[],
  enterpriseData: any,
  enterprisePhotos: any[]
}>()

const emit = defineEmits(['save', 'cancel', 'updateHealth', 'updateCertificates', 'updateEnterprise', 'updatePhotos'])

const editingHealth = ref<number | null>(null)

const localData = ref({ ...props.data })
const healthData = ref([...props.healthData])
const quarantineCertificates = ref([...props.quarantineCertificates])
const enterpriseData = ref({ ...props.enterpriseData })
const enterprisePhotos = ref([...props.enterprisePhotos])

// 养殖信息弹出框相关
const breedingDialogVisible = ref(false)
const breedingFormRef = ref()
const isEditMode = ref(false)
const breedingForm = ref({
  variety: '',
  source: '',
  feedingDays: null as number | null,
  feedBrand: '',
  responsiblePerson: '',
  productionDate: ''
})

// 表单验证规则
const breedingRules = {
  variety: [
    { required: true, message: '请填写品种', trigger: 'blur' },
    { 
      pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, 
      message: '品种只能包含中文和字母，不允许特殊字符', 
      trigger: 'blur' 
    },
    { max: 30, message: '品种最多30个字符', trigger: 'blur' }
  ],
  source: [
    { required: true, message: '请填写来源', trigger: 'blur' },
    { 
      pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, 
      message: '来源只能包含中文和字母，不允许特殊字符', 
      trigger: 'blur' 
    },
    { max: 30, message: '来源最多30个字符', trigger: 'blur' }
  ],
  feedingDays: [
    { required: true, message: '请填写饲养天数', trigger: 'blur' },
    { type: 'number', message: '饲养天数必须为数字', trigger: 'blur' },
    { min: 0, message: '饲养天数不能小于0', trigger: 'blur' },
    { max: 99999, message: '饲养天数不能超过99999', trigger: 'blur' }
  ],
  feedBrand: [
    { required: true, message: '请填写饲料品牌', trigger: 'blur' },
    { 
      pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, 
      message: '饲料品牌只能包含中文和字母，不允许特殊字符', 
      trigger: 'blur' 
    },
    { max: 30, message: '饲料品牌最多30个字符', trigger: 'blur' }
  ],
  responsiblePerson: [
    { required: true, message: '请填写饲养负责人', trigger: 'blur' },
    { 
      pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, 
      message: '饲养负责人只能包含中文和字母，不允许特殊字符', 
      trigger: 'blur' 
    },
    { max: 30, message: '饲养负责人最多30个字符', trigger: 'blur' }
  ],
  productionDate: [
    { required: true, message: '请选择出栏日期', trigger: 'change' }
  ]
}

watch(() => props.data, (val) => {
  localData.value = { ...val }
})

watch(() => props.healthData, (val) => {
  healthData.value = [...val]
})

watch(() => props.quarantineCertificates, (val) => {
  quarantineCertificates.value = [...val]
})

watch(() => props.enterpriseData, (val) => {
  enterpriseData.value = { ...val }
})

watch(() => props.enterprisePhotos, (val) => {
  enterprisePhotos.value = [...val]
})

// 养殖信息弹出框操作
const openBreedingDialog = () => {
  // 判断是添加还是修改模式
  const hasData = localData.value.variety || localData.value.source || localData.value.feedingDays || 
                  localData.value.feedBrand || localData.value.responsiblePerson || localData.value.productionDate
  
  isEditMode.value = !!hasData
  
  // 填充表单数据
  if (isEditMode.value) {
    // 修改模式：显示当前数据
    breedingForm.value = {
      variety: localData.value.variety || '',
      source: localData.value.source || '',
      feedingDays: localData.value.feedingDays || null,
      feedBrand: localData.value.feedBrand || '',
      responsiblePerson: localData.value.responsiblePerson || '',
      productionDate: localData.value.productionDate || ''
    }
  } else {
    // 添加模式：清空表单
    breedingForm.value = {
      variety: '',
      source: '',
      feedingDays: null,
      feedBrand: '',
      responsiblePerson: '',
      productionDate: ''
    }
  }
  
  breedingDialogVisible.value = true
  
  // 延迟清除验证状态
  nextTick(() => {
    if (breedingFormRef.value) {
      breedingFormRef.value.clearValidate()
    }
  })
}

const handleBreedingDialogClose = () => {
  breedingDialogVisible.value = false
  resetBreedingForm()
}

const handleBreedingBeforeClose = (done: () => void) => {
  // 检查是否有未保存的更改
  const hasChanges = breedingForm.value.variety || breedingForm.value.source || 
                    breedingForm.value.feedingDays || breedingForm.value.feedBrand || 
                    breedingForm.value.responsiblePerson || breedingForm.value.productionDate
  
  if (hasChanges) {
    ElMessageBox.confirm('确定关闭？未保存的数据将丢失', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      resetBreedingForm()
      done()
    }).catch(() => {
      // 取消关闭
    })
  } else {
    resetBreedingForm()
    done()
  }
}

const cancelBreedingDialog = () => {
  breedingDialogVisible.value = false
  resetBreedingForm()
  ElMessage.info('已取消操作')
}

const saveBreedingDialog = async () => {
  if (!breedingFormRef.value) {
    return
  }
  
  try {
    // 触发表单验证
    const valid = await new Promise<boolean>((resolve) => {
      breedingFormRef.value.validate((isValid: boolean) => {
        resolve(isValid)
      })
    })
    
    if (!valid) {
      ElMessage.warning('请填写所有必填字段')
      return
    }
    
    // 保存数据
    const savedData = { ...breedingForm.value }
    localData.value = { ...localData.value, ...savedData }
    
    // 发送到父组件
    emit('save', localData.value)
    
    // 关闭弹窗
    breedingDialogVisible.value = false
    resetBreedingForm()
    
    // 显示成功消息
    ElMessage.success(isEditMode.value ? '修改成功' : '添加成功')
    
  } catch (error) {
    ElMessage.error('保存失败，请重试')
  }
}

const resetBreedingForm = () => {
  breedingForm.value = {
    variety: '',
    source: '',
    feedingDays: null,
    feedBrand: '',
    responsiblePerson: '',
    productionDate: ''
  }
  
  if (breedingFormRef.value) {
    breedingFormRef.value.clearValidate()
  }
}

// 保健信息操作
const addHealth = () => {
  const newHealth = {
    id: Date.now(),
    feedingDays: null,
    healthMethod: '',
    healthApproach: '',
    isEditing: true
  }
  healthData.value.push(newHealth)
  editingHealth.value = newHealth.id
}

const editHealth = (row: any) => {
  row.isEditing = true
  editingHealth.value = row.id
}

const saveHealth = (row: any) => {
  // 验证必填字段
  if (!row.feedingDays || !row.healthMethod || !row.healthApproach) {
    ElMessage.warning('请填写所有必填字段')
    return
  }
  
  // 验证饲养天数
  if (row.feedingDays < 0 || row.feedingDays > 99999) {
    ElMessage.warning('饲养天数必须在0-99999之间')
    return
  }
  
  // 验证保健方式
  if (!/^[\u4e00-\u9fa5a-zA-Z]+$/.test(row.healthMethod)) {
    ElMessage.warning('保健方式只能包含中文和字母，不允许特殊字符')
    return
  }
  
  // 验证保健方法
  if (!/^[\u4e00-\u9fa5a-zA-Z]+$/.test(row.healthApproach)) {
    ElMessage.warning('保健方法只能包含中文和字母，不允许特殊字符')
    return
  }
  
  row.isEditing = false
  editingHealth.value = null
  emit('updateHealth', healthData.value)
  ElMessage.success('保健信息保存成功')
}

const cancelHealth = (row: any) => {
  // 如果是新添加的行，直接删除
  if (!row.id || row.id < 1000) {
    const index = healthData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      healthData.value.splice(index, 1)
    }
  } else {
    row.isEditing = false
  }
  editingHealth.value = null
  ElMessage.info('已取消编辑')
}

const deleteHealth = (row: any) => {
  ElMessageBox.confirm('确定要删除这条保健信息吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = healthData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      healthData.value.splice(index, 1)
      emit('updateHealth', healthData.value)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 验证函数
const validateFeedingDays = (row: any) => {
  if (row.feedingDays < 0) {
    row.feedingDays = 0
  } else if (row.feedingDays > 99999) {
    row.feedingDays = 99999
  }
}

const validateHealthMethod = (row: any) => {
  row.healthMethod = row.healthMethod.replace(/[^\u4e00-\u9fa5a-zA-Z]/g, '')
}

const validateHealthApproach = (row: any) => {
  row.healthApproach = row.healthApproach.replace(/[^\u4e00-\u9fa5a-zA-Z]/g, '')
}

// 动检证操作
const handleCertificateUpload = (file: File) => {
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  
  // 验证文件大小（5MB）
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }
  
  // 验证数量限制
  if (quarantineCertificates.value.length >= 9) {
    ElMessage.warning('最多只能上传9张动检证')
    return false
  }
  
  const newCert = {
    id: Date.now(),
    url: URL.createObjectURL(file),
    name: file.name
  }
  quarantineCertificates.value.push(newCert)
  emit('updateCertificates', quarantineCertificates.value)
  ElMessage.success('动检证上传成功')
  return false
}

const removeCertificate = (cert: any) => {
  const index = quarantineCertificates.value.findIndex(item => item.id === cert.id)
  if (index > -1) {
    quarantineCertificates.value.splice(index, 1)
    emit('updateCertificates', quarantineCertificates.value)
    ElMessage.success('动检证删除成功')
  }
}
</script>

<script lang="ts">
export default {
  name: 'BreedingInfo'
}
</script>

<style scoped>
.breeding-info {
  padding: 20px;
  overflow-y: auto;
}

.info-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.info-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.info-count {
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

.info-actions {
  display: flex;
  gap: 8px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item label {
  min-width: 100px;
  font-weight: 500;
  color: #606266;
}

.health-table {
  margin-top: 16px;
}

.certificate-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.certificate-item {
  position: relative;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.certificate-img {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.remove-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 10;
  background: rgba(0, 0, 0, 0.5);
  border: none;
  color: white;
}

.remove-btn:hover {
  background: rgba(245, 108, 108, 0.8);
}

.add-certificate {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 150px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.add-certificate:hover {
  border-color: #409eff;
}

.upload-area {
  text-align: center;
  color: #909399;
}

.upload-area .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.upload-tip {
  font-size: 12px;
  color: #c0c4cc;
  margin-top: 4px;
}

.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.image-placeholder .el-icon {
  font-size: 32px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .info-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .info-actions {
    justify-content: center;
  }
  
  .certificate-gallery {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
</style> 